package com.java.websocket.web.controler.websocket_work.Websocket;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.websocket.web.controler.websocket_work.Pojo.MessageData;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketServer extends TextWebSocketHandler{
    private final static ConcurrentHashMap<String,WebSocketSession> sessionMap = new ConcurrentHashMap<>();
    private final static ConcurrentHashMap<String,ConcurrentHashMap> chatSessionMap = new ConcurrentHashMap<>();
    private static String key;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String[] params = session.getUri().toString().split("=", 2);
        try {
            key = URLDecoder.decode(params[1], "UTF-8");
            System.out.println(key);
            sessionMap.put(session.getId(),session); // 新连接加入集合
            chatSessionMap.put(key,sessionMap);  //存入聊天室
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        MessageData messageData = mapper.readValue(message.getPayload(), MessageData.class);
        //判断聊天室中是否有该聊天群，如果有则群发
        if (chatSessionMap.containsKey(messageData.getName())){
            ConcurrentHashMap concurrentHashMap = chatSessionMap.get(messageData.getName());
            System.out.println(chatSessionMap.get(messageData.getName()));
            Collection<WebSocketSession> sessions = concurrentHashMap.values();
            for (WebSocketSession s : sessions) {
                s.sendMessage(new TextMessage(message.getPayload()));
            }
            System.out.println(message.getPayload());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        chatSessionMap.remove(key); // 连接关闭时移除
    }

}
